// 初始化webSocket
import { ref, onMounted, onBeforeUnmount, onUnmounted, toValue, watchEffect, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/index'
import Stomp from 'stompjs'
export function useWebsocket(url, method = 'get', params = {}) {
  let stompClient = null
  const socketData = ref({})
  const getSocketLinkInfo = () => {
    // console.log('getSocketLinkInfo')
    http(toValue(url), method, toValue(params)).then((res) => {
      if (res.status == 200) {
        const ws = new WebSocket(res.data.wsUrl)
        stompClient = Stomp.over(ws)
        stompClient.debug = () => {}
        stompClient.connect(
          { username: '' },
          () => {
            stompClient.subscribe(res.data.wsDestination, function (message) {
              socketData.value = JSON.parse(message.body)
            })
          },
          () => {
            console.log('stomp断开了')

            let timer = setTimeout(() => {
              useWebsocket(url, method, params)
              clearTimeout(timer)
            }, 2000)
          }
        )
      }
    })
  }
  onUnmounted(() => {
    if (stompClient) {
      try {
        stompClient.disconnect()
      } catch (error) {}
    }
  })

  watchEffect(() => {
    console.log('地址或参数发生了变化')
    //地址或参数发生了变化，先断开上次的连接
    if (stompClient) {
      try {
        stompClient.disconnect()
      } catch (error) {}
    }

    getSocketLinkInfo()
  })
  return { socketData }
}
